#include "Cannon.h"
#define PI 3.14f
#define R_GUN 33
#include "Box.h"
#include "Sprite.h"
#include "ShareComponents.h"
#include "RSManager.h"
#include "BulletManager.h"
#include "Camera.h"

Cannon::Cannon(Box* box):Object(box,Obj_STATIC)
{
	_isShooting=false;
}


Cannon::~Cannon(void)
{
}



void Cannon::init()
{
	_sAppear=RSManager::getInstance()->getSprite(EMBUSHGUN_APPEAR);
	_sGun=RSManager::getInstance()->getSprite(EMBUSHGUN_GUN);	
	_angle=PI;
	gl_player=gl_player;
	delay=0;
	_shoottime=0;
	_isShooting = false;
	_isStop = false;
	_sprite = NULL;
	index = 0;
	_bulletCount =BULLET_COUNT;
	_hits=8;
	_isAlive=true;
	_obj= Obj_STATIC;
	_state = C_UP;
	_sprite = _sAppear;
	_colBox->_v.x=0;
	_colBox->_v.y=0;
}
void Cannon::update()
{	
	if(_hits<0) _isAlive=false;
	switch (_state)
	{
	case C_UP:
		delay+=GAME_TIME;
		if(delay>300)
		{
			delay=0;
			_sprite->Next();
			if(_sprite->GetCurrentIndex()==2)
			{
				_state = C_ATTACK;
				_sprite = _sGun;
				_sprite->Reset(0);
			}

		}
		_colBox->_position.x=0;
		_colBox->_position.y=0;
		_colBox->_size.x=0;
		_colBox->_size.y=0;
		break;
	case C_DOWN:		
		if(_sprite == NULL) return;
		delay+=GAME_TIME;
		if (delay > 300)
		{
			if(_sprite->GetCurrentIndex() == 0)
			{
				_sprite = NULL;
				return;
			}
			delay = 0;
			_sprite->Last();
		}
		_colBox->_position.x=0;
		_colBox->_position.y=0;
		_colBox->_size.x=0;
		_colBox->_size.y=0;

		break;
	case C_ATTACK:
		if(_box->getLeft() < gl_camera->getLeftSide())
		{
			_sprite = _sAppear;
			_state = C_DOWN;
			delay  = 0;
			return;
		}
		D3DXVECTOR2 p = gl_player->getCenterPos() - _box->getCenterPos();
		float _agl = atan2(p.y,p.x);
		int index_sprite = getIndex(_agl);
		int dex;
		float angle = 0;
		if(index_sprite <= 5)
		{
			dex = 6;
			angle = 2.093f;
		}
		else
		{
			if(index_sprite >= 8)
			{
				dex = 8;
				angle = 3.14f;
			}
			else
			{
				dex = 7;
				angle = 2.6167f;
			}
		}
		_sprite->Reset(8 - dex);
		_shoottime += GAME_TIME;
		if(index_sprite > 8 || index_sprite < 5)
			{
				return;
		}
		if(_shoottime > 450)
		{			
			delay += GAME_TIME;
			if(delay > 150)
			{
				delay = 0;
				BulletManager::getInstance()->shoot(B_E,_obj,_box->getCenterPos(),angle);
				_bulletCount--;
			}
			if(_bulletCount <= 0)
			{
				_shoottime = 0;
				_bulletCount = 3;
			}
		}
		_colBox->_position=_box->_position;
		_colBox->_size = _box->_size;
		break;	
	}

}






void Cannon::render()
{	
	if(_sprite != NULL)
		_sprite->Render(_box->_position);
}

Box* Cannon::getCollisionBox()
{
	return _colBox;
}

int Cannon::getIndex(float _agl)
{
	if(_agl < 0.0f)
	{
		_agl = 2 * 3.14 + _agl;
	}
	return int(_agl * 8 / 3.14f);
}
